package com.neouton.crm.op.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.util.AuthUtils;
import com.neouton.common.util.Constants;
import com.neouton.common.util.PageUtil;
import com.neouton.common.util.ResponseAPI;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.impl.ApprovalServiceImpl;
import com.neouton.crm.cm.service.CostMigrateService;
import com.neouton.crm.entity.FileUploadRecordVO;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.op.entity.SalesOpportunityVO;
import com.neouton.crm.op.service.SalesOpportunityService;
import com.neouton.crm.pm.service.ProjectMemberService;
import com.neouton.crm.sales.entity.SalesChangeVO;
import com.neouton.crm.sales.entity.SalesFileRelationVO;
import com.neouton.crm.sales.entity.SalesFollowRecordVO;
import com.neouton.crm.sales.entity.SalesStageVO;
import com.neouton.crm.sales.service.SalesChangeService;
import com.neouton.crm.sales.service.SalesFileRelationService;
import com.neouton.crm.sales.service.SalesFollowRecordService;
import com.neouton.crm.sales.service.SalesStageService;
import com.neouton.feginClient.FileService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RequestMapping("opportunity")
@RestController
public class SalesOpportunityController {
    @Resource
    private SalesOpportunityService salesOpportunityService;
    @Resource
    private SalesStageService salesStageService;
    @Resource
    private SalesChangeService salesChangeService;
    @Resource
    private SalesFollowRecordService salesFollowRecordService;
    @Resource
    private SalesFileRelationService salesFileRelationService;
    @Resource
    private FileService fileService;
    @Resource
    private CostMigrateService costMigrateService;
    @Resource
    private ProjectMemberService projectMemberService;
    @Resource
    private ApprovalServiceImpl approvalService;

    /**
     * 分页查询机会信息
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunities/{page}/{limit}")
    public ResponseAPI queryOpportunities(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                          @PathVariable("page") Integer page,
                                          @PathVariable("limit") Integer limit,
                                          @RequestHeader("token") String token) {
        List<SysUserEntity> userList = projectMemberService.queryUserList(AuthUtils.getUserId(), Constants.OPPORTUNITY_MODEL_NAME, token);
        IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
        PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunity(pageInfo, salesOpportunityVO, userList, token);
        return ResponseAPI.successData(list);
    }

    /**
     * 分页查询机会信息     待办
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityToDo/{page}/{limit}")
    public ResponseAPI queryOpportunityToDo(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                          @PathVariable("page") Integer page,
                                          @PathVariable("limit") Integer limit,
                                          @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_AUDIT_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalByPage(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item:appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAudit(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询机会信息     已办
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityDone/{page}/{limit}")
    public ResponseAPI queryOpportunityDone(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                          @PathVariable("page") Integer page,
                                          @PathVariable("limit") Integer limit,
                                          @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_AUDIT_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAudit(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询机会信息     记录
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityRecord/{page}/{limit}")
    public ResponseAPI queryOpportunityRecord(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                          @PathVariable("page") Integer page,
                                          @PathVariable("limit") Integer limit,
                                          @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_AUDIT_TASK_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalRecordByType(approvalVO,token);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAudit(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询机会信息     待办  创建
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityToDoOne/{page}/{limit}")
    public ResponseAPI queryOpportunityToDoOne(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                            @PathVariable("page") Integer page,
                                            @PathVariable("limit") Integer limit,
                                            @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_CREATE_AUDIT_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalByPage(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item:appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAuditOne(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询机会信息     已办  创建
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityDoneOne/{page}/{limit}")
    public ResponseAPI queryOpportunityDoneOne(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                            @PathVariable("page") Integer page,
                                            @PathVariable("limit") Integer limit,
                                            @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_CREATE_AUDIT_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalDoneRecordByType(approvalVO);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAuditOne(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 分页查询机会信息     记录  创建
     * @param salesOpportunityVO
     * @param page
     * @param limit
     * @param token
     * @return
     */
    @PostMapping("/queryOpportunityRecordOne/{page}/{limit}")
    public ResponseAPI queryOpportunityRecordOne(@RequestBody SalesOpportunityVO salesOpportunityVO,
                                              @PathVariable("page") Integer page,
                                              @PathVariable("limit") Integer limit,
                                              @RequestHeader("token") String token) {
        ApprovalVO approvalVO = new ApprovalVO();
        approvalVO.setApprovalType(Constants.OPPORTUNITY_CREATE_AUDIT_TYPE);
        List<ApprovalVO> appList = approvalService.queryApprovalRecordByType(approvalVO,token);
        if (appList == null || appList.isEmpty()) {
            return ResponseAPI.successData(new PageUtil(new PageDTO()));
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (ApprovalVO item : appList) {
                arrayList.add(item.getApprovalId());
            }
            salesOpportunityVO.setApprovalList(arrayList);
            IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
            PageUtil<SalesOpportunityVO> list = salesOpportunityService.queryOpportunityAuditOne(pageInfo, salesOpportunityVO, null, token);
            return ResponseAPI.successData(list);
        }
    }

    /**
     * 查询机会信息
     *
     * @param salesOpportunityVO
     * @return
     */
    @PostMapping("/queryOpportunityInfo")
    public ResponseAPI queryOpportunityInfo(@RequestBody SalesOpportunityVO salesOpportunityVO, @RequestHeader("token") String token) {
        List<SysUserEntity> userList = projectMemberService.queryUserList(AuthUtils.getUserId(), "opportunity", token);
        List<SalesOpportunityVO> list = salesOpportunityService.queryOpportunity(salesOpportunityVO, userList, token);
        return ResponseAPI.successData(list);
    }

    /**
     * 单机会查询
     *
     * @param opId 机会ID
     * @return
     */
    @PostMapping("/queryOpportunityById/{opId}")
    public ResponseAPI queryOpportunityById(@PathVariable("opId") Integer opId,
                                            @RequestHeader("token") String token) {
        SalesOpportunityVO result = salesOpportunityService.queryOpportunityById(opId);
        return ResponseAPI.successData(result);
    }


    /**
     * 单机会查询
     *
     * @param opId 机会ID
     * @return
     */
    @PostMapping("/queryOpportunityByApprovalId/{approvalId}")
    public ResponseAPI queryOpportunityByApprovalId(@PathVariable("approvalId") Integer approvalId,
                                            @RequestHeader("token") String token) {
        SalesOpportunityVO result = salesOpportunityService.queryOpportunityByApprovalId(approvalId);
        return ResponseAPI.successData(result);
    }

    /**
     * 单机会查询
     *
     * @param opId 机会ID
     * @return
     */
    @PostMapping("/queryOpportunityHistoryByApprovalId/{approvalId}")
    public ResponseAPI queryOpportunityHistoryByApprovalId(@PathVariable("approvalId") Integer approvalId,
                                                    @RequestHeader("token") String token) {
        SalesOpportunityVO result = salesOpportunityService.queryOpportunityHistoryByApprovalId(approvalId);
        return ResponseAPI.successData(result);
    }

    /**
     * 单机会查询
     *
     * @param opId 机会ID
     * @return
     */
    @PostMapping("/queryOpportunityAllById/{opId}")
    public ResponseAPI queryOpportunityAllById(@PathVariable("opId") Integer opId) {
        SalesOpportunityVO result = salesOpportunityService.queryOpportunityAllById(opId);
        return ResponseAPI.successData(result);
    }

    // 新增机会
    @PostMapping("/saveOpportunity")
    @Transactional
    public ResponseAPI saveOpportunity(@RequestBody SalesOpportunityVO record, @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.saveOpportunity(record, token));
    }


    // 新增机会
    @PostMapping("/updateOpportunityByCreate")
    @Transactional
    public ResponseAPI updateOpportunityByCreate(@RequestBody SalesOpportunityVO record, @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.updateOpportunityByCreate(record, token));
    }


    public Boolean toVerifyCost(Integer opportunityId, String token) {
        return costMigrateService.verifyCost(opportunityId, token);
    }

    @PostMapping("/verifyCost/{opportunityId}")
    public ResponseAPI verifyCost(@PathVariable("opportunityId") Integer opportunityId, @RequestHeader("token") String token) {
        return ResponseAPI.successData(toVerifyCost(opportunityId, token));
    }

    /**
     * 修改机会，接口返回修改后的机会
     * 状态发生变化会走审批
     */
    @PostMapping("/updateOpportunity")
    public ResponseAPI updateOpportunity(@RequestBody SalesOpportunityVO toOp,
                                         @RequestHeader("token") String token) {
//        if (costMigrateService.verifyCost(toOp.getOpportunityId(), token)) {
//            return ResponseAPI.successData("有费用未迁移");
//        }
        // 发生变更前的机会信息
        SalesOpportunityVO fromOp = salesOpportunityService.queryOpportunityById(toOp.getOpportunityId());
        if (fromOp.getAuditState() == 0) {       // 审批中不允许修改，防止页面数据超时
            return ResponseAPI.successData("当前机会正在审批中");
        }
        toOp.setLastUpdateBy(AuthUtils.getUserId());
        if (toOp.getOpportunityState() == 2) {
            toOp.setStageStateId(6);
        } else if (toOp.getOpportunityState() == 3 || toOp.getOpportunityState() == 4) {
            toOp.setStageStateId(7);
        }
        boolean updateSuccess = salesOpportunityService.updateByPrimaryKey(toOp);
        SalesOpportunityVO resultOp = salesOpportunityService.queryOpportunityById(toOp.getOpportunityId());
        if (updateSuccess) {
            salesOpportunityService.createRecord(fromOp, resultOp, token);
//            if (toOp.getOpportunityState() == 2 || !Objects.equals(fromOp.getStageStateId(), resultOp.getStageStateId())) {
//                // 保存机会时会插入一条阶段变更记录     成功状态时   非成功但阶段变更时
//                SalesStageVO salesStageVO = new SalesStageVO();
//                salesStageVO.setStageClass(Constants.OPPORTUNITY_MODEL_ID);
//                salesStageVO.setSalesRelationId(toOp.getOpportunityId());
//                salesStageVO.setCreator(toOp.getCreator());
//                salesStageVO.setCreateDataTime(toOp.getStageUpdateTime());
//                salesStageVO.setStageStateId(toOp.getStageStateId());
//                salesStageService.insert(salesStageVO);
//            }
            // 状态发生改变走工作流进行审批   失败或放弃走审批
            if (toOp.getOpportunityState() != 1 && toOp.getOpportunityState() != 2) {
                resultOp.setOpportunityStateBack(fromOp.getOpportunityState());
                resultOp.setOpportunityState(toOp.getOpportunityState());
                SalesOpportunityVO result = salesOpportunityService.commitStateChangeToAudit(resultOp, token);
                return ResponseAPI.successData(result);
            }

            if(toOp.getOpportunityState() != 2){
                //删除对应项目信息
                projectMemberService.deleteProjectByOppId(toOp.getOpportunityId());
            }
        }
        return ResponseAPI.successData(resultOp);
    }

    // 删除机会
    @PostMapping("/deleteOpportunity/{opId}")
    public ResponseAPI deleteOpportunity(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(salesOpportunityService.logicDelete(opId));
    }

    // 查询跟进记录
    @PostMapping("/queryFollowRecords/{opId}")
    public ResponseAPI queryFollowRecords(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(salesFollowRecordService.queryFollowRecord(opId, Constants.OPPORTUNITY_MODEL_ID));
    }

    // 保存跟进记录
    @PostMapping("/saveFollowRecord")
    public ResponseAPI saveFollowRecords(@RequestBody SalesFollowRecordVO followRecord) {
        followRecord.setFollowClass(Constants.OPPORTUNITY_MODEL_ID);
        followRecord.setCreator(AuthUtils.getUserId());
        return ResponseAPI.successData(salesFollowRecordService.insert(followRecord));
    }

    /**
     * 删除机会点跟进记录
     *
     * @param recordId 记录ID
     * @return boolean 删除是否成功
     */
    @PostMapping("/deleteFollowRecord/{recordId}")
    public ResponseAPI deleteFollowRecords(@PathVariable("recordId") Integer recordId) {
        return ResponseAPI.successData(salesFollowRecordService.removeById(recordId));
    }

    /**
     * 阶段推进
     *
     * @param salesStageVO 推进到的状态对象
     * @return boolean 阶段推进是否成功
     */
    @PostMapping("/changeStage")
    public ResponseAPI changeStage(@RequestBody SalesStageVO salesStageVO) {
        SalesOpportunityVO op = salesOpportunityService.queryOpportunityById(salesStageVO.getSalesRelationId());
        if (Objects.equals(op.getStageStateId(), salesStageVO.getStageStateId())) {
            return ResponseAPI.successData(false);
        }
        salesStageVO.setStageClass(Constants.OPPORTUNITY_MODEL_ID);
        salesStageVO.setCreator(AuthUtils.getUserId());
        salesStageService.changeStage(salesStageVO);
        return ResponseAPI.successData(true);
    }

    // 阶段变更记录查询
    @PostMapping("/queryStageChange/{opId}")
    public ResponseAPI queryStageChange(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(salesStageService.queryStageInfo(opId, Constants.OPPORTUNITY_MODEL_ID));
    }

    // 日志查询
    @PostMapping("/queryChangeLog/{opId}")
    public ResponseAPI queryChangeLog(@PathVariable("opId") Integer opId) {
        return ResponseAPI.successData(salesChangeService.queryOppAnProChangeInfo(opId));
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @param opId 机会点ID
     * @return 上传的文件记录、用于前端构造fileList
     */
    @PostMapping("/uploadFile/{opId}")
    public ResponseAPI uploadFileForOpportunity(@RequestParam("file") MultipartFile file,
                                                @PathVariable("opId") Integer opId,
                                                @RequestHeader("token") String token) {
        // 调用远程上传服务
        FileUploadRecordVO fileUploadRecordVO = fileService.upload2Ftp(file, token).getResult();
        // 将结果进行记录
        SalesFileRelationVO salesFileRelationVO = new SalesFileRelationVO();
        salesFileRelationVO.setSalesRelationId(opId);
        salesFileRelationVO.setFileClass(Constants.OPPORTUNITY_MODEL_ID);
        salesFileRelationVO.setCreator(AuthUtils.getUserId());
        // salesFileRelationVO.setCreateDataTime(new Timestamp(fileUploadRecordVO.getUploadTime().getTime()));
        salesFileRelationVO.setFileId(fileUploadRecordVO.getId());
        salesFileRelationVO.setFileName(fileUploadRecordVO.getOriFileName());
        salesFileRelationVO.setContentType(fileUploadRecordVO.getContentType());
        salesFileRelationVO.setFlag(1);
        salesFileRelationService.save(salesFileRelationVO);
        return ResponseAPI.successData(salesFileRelationVO);
    }

    /**
     * 附件逻辑删除、更新人为删除人，更新时间为删除时间
     *
     * @param salesFileId 需要删除的文件的主键ID
     * @param token
     * @return boolean 是否删除成功
     */
    @PostMapping("/deleteFile/{salesFileId}")
    public ResponseAPI deleteFile(@PathVariable("salesFileId") String salesFileId,
                                  @RequestHeader("token") String token) {
//        SalesFileRelationVO file = salesFileRelationService.selectByPrimaryKey(salesFileId);
//        file.setLastUpdateBy(AuthUtils.getUserId());
        return ResponseAPI.successData(salesFileRelationService.deleteFileInfo(salesFileId, Constants.OPPORTUNITY_MODEL_ID));
    }

    /**
     * 附件逻辑删除、更新人为删除人，更新时间为删除时间
     *
     * @param salesFileId 需要删除的文件的主键ID
     * @param token
     * @return boolean 是否删除成功
     */
    @PostMapping("/deleteFileBySalesFileId/{salesFileId}")
    public ResponseAPI deleteFileBySalesFileId(@PathVariable("salesFileId") String salesFileId) {
//        SalesFileRelationVO file = salesFileRelationService.selectByPrimaryKey(salesFileId);
//        file.setLastUpdateBy(AuthUtils.getUserId());
        return ResponseAPI.successData(salesFileRelationService.deleteFileBySalesFileId(salesFileId));
    }

    /**
     * 待办信息查询
     */
    @PostMapping("/queryToDoList/{page}/{limit}")
    public ResponseAPI queryToDoList(@RequestBody SalesOpportunityVO op,
                                     @PathVariable("page") Integer page,
                                     @PathVariable("limit") Integer limit,
                                     @RequestHeader("token") String token) {
        IPage<SalesOpportunityVO> pageInfo = new Page<>(page, limit, true);
        PageUtil<SalesOpportunityVO> result = salesOpportunityService.queryToDoList(pageInfo, op);
        return ResponseAPI.successData(result);
    }

    /**
     * 根据工作流ID查询机会点信息
     */
    @PostMapping("/queryOpportunityByBusinessId/{businessId}")
    public ResponseAPI queryOpportunityByBusinessId(@PathVariable("businessId") Integer businessId,
                                                    @RequestHeader("token") String token) {
//        QueryWrapper<SalesOpportunityVO> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("business_id", businessId);
//        Integer id = salesOpportunityService.getOne(queryWrapper).getOpportunityId();
//        return queryOpportunityById(id, token);
        return ResponseAPI.successData(salesOpportunityService.queryOpportunityByBusinessId(businessId));
    }

    // 机会状态变更审核通过
    @PostMapping("/approveStateChange")
    public ResponseAPI approveStateChange(@RequestBody SalesOpportunityVO op,
                                          @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.approveStateChange(op, token,false));
    }

    // 机会状态变更审核通过
    @PostMapping("/approveCreateOp")
    public ResponseAPI approveCreateOp(@RequestBody SalesOpportunityVO op,
                                          @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.approveCreateOp(op, token,false));
    }

    // 机会状态变更审核驳回至上一节点
    @PostMapping("/rejectStateChange")
    public ResponseAPI rejectStateChange(@RequestBody SalesOpportunityVO op,
                                         @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.rejectStateChange(op, token));
    }

    // 机会状态变更审核驳回至上一节点
    @PostMapping("/rejectCreateOp")
    public ResponseAPI rejectCreateOp(@RequestBody SalesOpportunityVO op,
                                         @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.rejectCreateOp(op, token));
    }

    /**
     * 向项目管理模块提供
     * 获取stateCode状态的所有审核通过的机会
     *
     * @return 所有匹配的机会点集合
     */
    @PostMapping("/queryOpportunitiesByState")
    public ResponseAPI queryOpportunitiesByState(@RequestBody SalesOpportunityVO param,
                                                 @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.selectAllOpInfo(param));
    }

    /**
     * 导出Excel
     *
     * @param response
     * @param entity
     * @throws Exception
     */
    @PostMapping("/exportOpportunityInfo")
    public void exportOpportunityInfo(HttpServletResponse response, @RequestBody SalesOpportunityVO entity,
                                      @RequestHeader("token") String token) throws Exception {
//        Integer userId = AuthUtils.getUserId();
//        int authId = projectMemberService.queryAuth(userId,Constants.OPPORTUNITY_MODEL_NAME);
        List<SysUserEntity> userList = projectMemberService.queryUserList(AuthUtils.getUserId(), "opportunity", token);
        List<SalesOpportunityVO> list = salesOpportunityService.queryOpportunity(entity, userList, token);
        salesOpportunityService.exportOpportunityInfo(response, list, token);
    }

    /**
     * 根据工作流ID查询申请记录
     */
    @PostMapping("/queryHistoryOpportunityByApprovalId/{approvalId}")
    public ResponseAPI queryHistoryOpportunityByApprovalId(@PathVariable("approvalId") Integer approvalId,
                                                           @RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.queryHistoryOpportunityByApprovalId(approvalId));
    }

    /**
     * 更具ID获取机会负责人信息
     *
     * @return
     */
    @PostMapping("/queryOpportunityHeadByProjectId/{opportunityId}")
    public ResponseAPI queryOpportunityHeadByProjectId(@PathVariable(value = "opportunityId") Integer opportunityId,@RequestHeader("token") String token) {
        SysUserEntity header = salesOpportunityService.queryOpportunityHeadByProjectId(opportunityId,token);
        return ResponseAPI.successData(header);
    }

    /**
     * 转移负责人
     * @param userId
     * @param voList
     * @param token
     * @return
     */
    @PostMapping("/transforPrincipal/{userId}")
    public ResponseAPI transforPrincipal(@PathVariable(value = "userId") Integer userId,@RequestBody List<SalesOpportunityVO> voList,@RequestHeader("token") String token) {
        return ResponseAPI.successData(salesOpportunityService.transforPrincipal(userId,voList,token));
    }
}
